package com.cb2.algorithm.leetcode;

/**
 * <a href="https://leetcode.cn/problems/container-with-most-water/">盛最多水的容器(Container With Most Water)</a>
 * <p>给定一个长度为 n 的整数数组 height 。有 n 条垂线，第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。
 * 找出其中的两条线，使得它们与 x 轴共同构成的容器可以容纳最多的水。</p>
 * <p>
 * 返回容器可以储存的最大水量。</p>
 * <b>说明：</b>你不能倾斜容器。
 * <p>
 * <b>示例</b>
 * <pre>
 * 示例 1：
 *      |         _                        _
 *      |        | |                      | |        _
 *      |        | |   _                  | |       | |
 *      |        | |  | |        _        | |       | |
 *      |        | |  | |       | |   _   | |       | |
 *      |        | |  | |       | |  | |  | |   _   | |
 *      |        | |  | |   _   | |  | |  | |  | |  | |
 *      |    _   | |  | |  | |  | |  | |  | |  | |  | |
 *      |___|_|__|_|__|_|__|_|__|_|__|_|__|_|__|_|__|_|_
 *      输入：[1,8,6,2,5,4,8,3,7]
 *      输出：49
 *      解释：图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下，容器能够容纳水（表示为蓝色部分）的最大值为 49。
 *
 * 示例 2：
 *      |   _    _
 *      |__|_|__|_|_
 *      输入：height = [1,1]
 *      输出：1
 *     </pre>
 * </p>
 * <p>
 * <b>提示：</b>
 * <ul>
 *     <li>n == height.length</li>
 *     <li>2 <= n <= 10^5</li>
 *     <li>0 <= height[i] <= 10^4</li>
 * </ul>
 * </p>
 *
 * @author c2b
 * @since 2023/10/11 9:53
 */
public class LC0011ContainerWithMostWater_M {
    static class Solution {
        public int maxArea(int[] height) {
            int leftIndex = 0;
            int rightIndex = height.length - 1;
            int maxArea = 0;
            while (leftIndex < rightIndex) {
                int leftHeight = height[leftIndex];
                int rightHeight = height[rightIndex];
                maxArea = Math.max(maxArea, Math.min(leftHeight, rightHeight) * (rightIndex - leftIndex));

                if (leftHeight < rightHeight) {
                    do {
                        ++leftIndex;
                    }
                    while (leftIndex < rightIndex && leftHeight >= height[leftIndex]);
                } else {
                    do {
                        --rightIndex;
                    } while (leftIndex < rightIndex && rightHeight >= height[rightIndex]);
                }
            }
            return maxArea;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.maxArea(new int[]{1, 8, 6, 2, 5, 4, 8, 3, 7}));
        System.out.println(solution.maxArea(new int[]{1, 1}));
        System.out.println(solution.maxArea(new int[]{1, 2, 1}));
    }
}